<template>
  <el-input
      id="msgbox"
      v-model="messages"
      :rows="rows"
      type="textarea"
      placeholder="Please input"
      readonly
      stretch
  />
</template>

<script>
export default {
  name: "WebsocketPanel",
  props:["uuid","rows","messageSize"],
  data(){
    return {
      messageArray:[],
      cursor:0,
      lines:0
    }
  },
  computed:{
    messages(){
      let msg1=[],msg2=[]
      let index=this.cursor
      msg1=this.messageArray.slice(index)
      if(index>0)
        msg2=this.messageArray.slice(0,index)
      return (msg1[0]?(msg1.join("\n")+"\n"):"")+(msg2.length>0?msg2.join("\n"):"")
    }
  },
  created(){
    this.initWebsocket()
  },
  methods:{
    initWebsocket(){
      if (typeof WebSocket === "undefined") {
        this.$message({
          message:"您的浏览器不支持socket",
          type: "error",
          duration:2000
        })
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.$websocketBaseUrl+"/"+this.uuid);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
        this.socket.onclose=this.close;
      }
    },
    // socket连接成功
    open() {
      console.log("socket连接成功");
    },
// socket连接失败
    error() {
      console.log("连接错误");
    },
// 接收消息
    getMessage(msg) {
      console.log("==websocket接收数据==\t"+msg.data);
      this.lines++
      this.messageArray[this.cursor++]="No."+this.lines+"["+this.getTime()+"] :\t"+msg.data
      this.$nextTick(()=>{
        let textarea = document.getElementById("msgbox")
        textarea.scrollTop = textarea.scrollHeight
      })
      if(this.cursor==this.messageSize)
        this.cursor=0
    },
    getTime(){
      let date=new Date()
      return date.getFullYear()+""+this.zeroStr(date.getMonth()+1)+""+this.zeroStr(date.getDate())+""+this.zeroStr(date.getHours())+""+this.zeroStr(date.getMinutes())+""+this.zeroStr(date.getSeconds())
    },
    zeroStr(num){
      return num<10?("0"+num):num
    },
// 发送数据
    send() {
      this.socket.send("这是传送数据");
    },
// 关闭socket
    close() {
      console.log("socket已经关闭");
    },
  },
  unmounted() {
    if( typeof this.socket != "string") {
      this.socket.close()
    }
  }
}
</script>

<style scoped>

</style>